const app = getApp();

Page({
  data: {
    list: [],
    stats: null,
    yearMonth: '',
    page: 1,
    limit: 20,
    hasMore: true
  },

  onLoad() {
    const now = new Date();
    const yearMonth = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0');
    
    this.setData({
      yearMonth
    });
    
    this.loadData();
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      list: [],
      hasMore: true
    });
    this.loadData(() => {
      wx.stopPullDownRefresh();
    });
  },

  onMonthChange(e) {
    this.setData({
      yearMonth: e.detail.value,
      page: 1,
      list: [],
      hasMore: true
    });
    this.loadData();
  },

  loadData(callback) {
    const userInfo = app.globalData.userInfo || wx.getStorageSync('userInfo');
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '加载中...' });
    
    // 加载考勤列表
    wx.request({
      url: app.globalData.userApiUrl + '/getAttendanceList',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + app.globalData.token
      },
      data: {
        user_id: userInfo.id,
        page: this.data.page,
        limit: this.data.limit,
        year_month: this.data.yearMonth
      },
      success: (res) => {
        if (res.data.code === 1) {
          const newList = res.data.data.list || [];
          
          this.setData({
            list: this.data.page === 1 ? newList : [...this.data.list, ...newList],
            hasMore: newList.length >= this.data.limit
          });
        }
      },
      complete: () => {
        wx.hideLoading();
        if (callback) callback();
      }
    });
    
    // 加载月度统计
    wx.request({
      url: app.globalData.userApiUrl + '/getAttendanceStatistics',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + app.globalData.token
      },
      data: {
        user_id: userInfo.id,
        year_month: this.data.yearMonth
      },
      success: (res) => {
        if (res.data.code === 1) {
          this.setData({
            stats: res.data.data.stats
          });
        }
      }
    });
  },

  loadMore() {
    if (!this.data.hasMore) return;
    
    this.setData({
      page: this.data.page + 1
    });
    this.loadData();
  }
});
